package com.ganbo.demo.caffeine.service;


import com.ganbo.demo.caffeine.pojo.User;
import com.ganbo.demo.caffeine.utils.FastJsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    RedisService redisService;

    @Autowired
    CacheManager cacheManager;

    public void init() {
        for (int i = 1; i < 11; i++) {
            User user = new User(i, "user_" + i);
            redisService.hset("users", i + "", FastJsonUtil.objectTOJsonString(user));
        }
    }

    @Cacheable(cacheManager = "oneHourCacheManager", value = "users", key = "#id")
    public User get(Integer id) {
        String userStr = redisService.hget("users", id.toString());
        System.out.println("去redis查询....");
        User user = FastJsonUtil.jsonStringToObject(userStr, User.class);

        for (String cacheName : cacheManager.getCacheNames()) {
            System.out.println(cacheName);
        }

        return user;
    }
}

